<?php
 #this page will update the database and load the next(selected) race onto the 
 #Race table ready to start betting on the next race
 #it also ensure the winners and payout amount is stored in the last races table
$r = $_POST['Race'] ;
$Hnum = $_POST['horse_num'];

  
 
$name_es = sqlite_escape_string($name);
echo $Hnum ;
echo "<br>";
$n="race";
echo "this should be a number ".$r;
 echo "<br>";
 $lr = $r-1;
 $rn=$n.$r;
echo $r;
echo "<br>";
echo $lr;
echo "<br>";
 $lrn = $n.$lr;
 echo $lrn;
#if (!empty($hname)) {

   $db = sqlite_open('horse.db', 0666, $error);
   #Write winner  data into last race db in decimal odds cell, and add payout data
$cresult=sqlite_query($db,"SELECT payout from race Where horse_num = $Hnum");
 $res = sqlite_fetch_single($cresult)  ;
 Echo "payout";
 echo $res;
 $stm = "UPDATE $lrn SET payout ='$res' WHERE horse_num = '$Hnum'";
   $ok = sqlite_query($db, $stm, $error);  
   if (!$ok) die("Error: $error"); 
 $stm = "UPDATE $lrn SET decimal_odds = '1' WHERE horse_num = '$Hnum'";
   $ok = sqlite_query($db, $stm, $error);  
   if (!$ok) die("Error: $error");       
#Read Data from requested race
# set horse number
$hn =1 ;
$result = sqlite_array_query($db, "SELECT * FROM $rn", SQLITE_ASSOC);
foreach ($result as $entry) {
  #echo 'Horse: ' . $entry['horse_num'] .' ' . $entry['horse_name'].' :- '.'number of bets : '. $entry['bets'] .':- '.' Payout :'. $entry['payout'].'<br>';
  $Hname = $entry['horse_name'];
   #if (!$dbhandle) die ($error);
  # # write this into the current race database  
   $stm = "UPDATE race SET horse_name ='$Hname' WHERE horse_num = '$hn'";
   $ok = sqlite_query($db, $stm, $error);
    #echo $stm;
   if (!$ok) die("Error: $error");  
    
   #increase hn to change horse names
   $hn++;
   #echo $hn;
}
sqlite_query($db, "UPDATE race SET payout ='0'",$sqliteerror);
sqlite_query($db, "UPDATE race SET bets ='0'",$sqliteerror);
sqlite_query($db, "UPDATE race SET bets ='$r' where horse_num = '9'",$sqliteerror);
sqlite_close($db); 
echo <<<endHTML
<html>
<head><title>Race-update</title></head>
<body>
<center>
back to tote entry page
<a href="tote.php"> click here</a>
endHTML;
?>